<template>
  <div class="h-full">
    <n-card class="h-full rounded-16px shadow-sm" :bordered="false">
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-button type="primary" size="small" @click="handleAdd">
            <icon-ic-round-plus class="mr-4px text-20px" />新增账号
          </n-button>
        </n-space>
        <n-space>
          <n-form :model="filterModel" inline :show-label="false" :show-feedback="false">
            <n-form-item label="手机号码" path="userPhone">
              <n-input
                v-model:value="filterModel.userPhone"
                placeholder="手机号码"
                clearable
                size="small"
                class="ml-30px w-120px"
              />
            </n-form-item>
            <n-form-item>
              <n-button size="small" type="primary" @click="handleFilter">
                <icon-tabler:search class="mr-5px" />
                查询
              </n-button>
            </n-form-item>
          </n-form>
        </n-space>
      </n-space>
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :single-line="false"
        size="small"
        striped
      />
    </n-card>
    <edit-modal v-model:visible="visible" :type="modalType" :edit-data="editData" />
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import type { PaginationProps, DataTableColumn } from 'naive-ui';
import { fetchUserList, fetchDeleteUser } from '@/service';
import { useAppStore } from '@/store';
import { useBoolean, useLoading } from '@/hooks';
import editModal from './components/EditModal.vue';

// 初始加载、模态窗口状态
const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();

// 处理接口数据
const tableData: any = ref([]);
function setTableData(data: any) {
  tableData.value = data;
}

// 配置查询参数
const filterModel = ref({
  userPhone: ''
});

// 获取接口数据并处理加载状态
async function getTableData() {
  startLoading();
  const { data } = await fetchUserList(filterModel.value);
  if (data) {
    setTableData(data);
    endLoading();
  }
}

function handleFilter() {
  const { userPhone } = filterModel.value;
  if (userPhone) {
    getTableData();
  } else {
    window.$message?.error(`请输入手机号码`);
  }
}

// 配置分页
const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  suffix({ itemCount }) {
    return `共${itemCount}条记录`;
  },
  onChange: (page: number) => {
    pagination.page = page;
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
  }
});

const columns: DataTableColumn[] = [
  {
    title: '账号ID',
    key: 'userId',
    align: 'center'
  },
  {
    key: 'phone',
    title: '手机号码',
    width: 200,
    align: 'center',
    sorter: 'default'
  },
  {
    key: 'userName',
    title: '姓名',
    width: 200,
    align: 'center',
    sorter: 'default'
  },
  {
    key: 'supplierName',
    title: '供应商',
    align: 'center',
    sorter: 'default'
  },
  {
    key: 'organizationName',
    title: '组织',
    align: 'center',
    sorter: 'default'
  },
  {
    key: 'userStatus',
    title: '账号状态',
    width: 100,
    align: 'center',
    sorter: 'default',
    render: (row: any) => {
      if (row.userStatus) {
        const u: number = parseInt(row.userStatus, 10);
        const tagTypes: any = {
          0: 'error',
          1: 'success'
        };
        const tagNames: any = {
          0: '已禁用',
          1: '启用中'
        };
        return (
          <NTag round size="small" type={tagTypes[u]}>
            {tagNames[u]}
          </NTag>
        );
      }
      return '';
    }
  },
  {
    key: 'actions',
    title: '操作',
    align: 'center',
    width: 120,
    render: (row: any) => {
      return (
        <NSpace justify="center">
          <NButton size="tiny" secondary type="primary" onClick={() => handleEdit(row)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.userId)}>
            {{
              default: () => '确认删除',
              trigger: () => (
                <NButton size="tiny" secondary type="warning">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </NSpace>
      );
    }
  }
];

const modalType: any = ref('add');
function setModalType(type: any) {
  modalType.value = type;
}

const editData: any = ref(null);
function setEditData(data: any) {
  editData.value = data;
}

function handleAdd() {
  setModalType('add');
  openModal();
}

function handleEdit(row: object) {
  setEditData(row);
  setModalType('edit');
  openModal();
}

const app = useAppStore();
async function handleDelete(rowId: string) {
  const res: any = await fetchDeleteUser(rowId);
  if (res.data) {
    window.$message?.info(`账号ID ${res.data.userId} 删除成功`);
    app.reloadPage();
  }
}

function init() {
  getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
